package myzzyl.service.Impl;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import myzzyl.constants.CommonStrField;
import myzzyl.domain.pojo.SysUserRole;
import myzzyl.properties.SecurityConfigProperties;
import myzzyl.service.SysRoleResourceService;
import myzzyl.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {


    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleResourceService sysRoleResourceService;

    @Autowired
    private SecurityConfigProperties securityConfigProperties;

    // 返回一个账号所拥有的权限码集合
    @Override
//    @SuppressWarnings("unchecked")
    public List<String> getPermissionList(Object loginId, String loginType) {

        // 1. 声明权限码集合
        List<String> list = new ArrayList<>();

        // 2. 遍历角色列表，查询拥有的权限码
        for (String roleId : getRoleList(loginId, loginType)) {
            String permissions = SaManager.getSaTokenDao().get(CommonStrField.USER_RESOURCE.getStr() + roleId);
            List<String> permissionList = JSONUtil.toList(permissions, String.class);

            // 判断是否为空，为空才去数据库里查询
            if(CollectionUtil.isEmpty(permissionList)) {
                // 从数据库查询这个角色 id 所拥有的权限列表
                permissionList = sysRoleResourceService.selectResourceRequestPathByRoleId(Long.valueOf(roleId));
                // 查好后，set 到缓存中
                SaManager.getSaTokenDao().set(CommonStrField.USER_RESOURCE.getStr() + roleId, JSONUtil.toJsonStr(permissionList), 60 * 60 * 24 * 7);
            }
            list.addAll(permissionList);
        }

        // 添加白名单访问资源
        list.addAll(securityConfigProperties.getPublicAccessUrls());

        // 3. 返回权限码集合
        return list;
    }

    // 返回一个账号所拥有的角色标识集合
    @Override
//    @SuppressWarnings("unchecked")
    public List<String> getRoleList(Object loginId, String loginType) {
        String roles = SaManager.getSaTokenDao().get(CommonStrField.USER_ROLE.getStr() + loginId);
        List<String> roleList = JSONUtil.toList(roles, String.class);

        // 判断是否为空，为空才去数据库里查询
        if(CollectionUtil.isEmpty(roleList)) {
            // 从数据库查询这个账号id拥有的角色列表，
            roleList = sysUserRoleService
                    .lambdaQuery()
                    .eq(SysUserRole::getUserId, loginId)
                    .list()
                    .stream().map(sysUserRole -> sysUserRole.getRoleId().toString())
                    .toList();
            // 查好后，set 到缓存中
            SaManager.getSaTokenDao().set(CommonStrField.USER_ROLE.getStr() + loginId, JSONUtil.toJsonStr(roleList), 60 * 60 * 24 * 7);
        }
        return roleList;
    }

}
